//
//  TXFModelViewController.swift
//  weibo飞飞
//
//  Created by 田侠飞 on 16/7/3.
//  Copyright © 2016年 田侠飞. All rights reserved.
//

import UIKit

class TXFModelViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        
    setupUI()
      
        
        
        
        
        
    }
    
    
    func  setupUI(){
    setupNav()
        
     //添加控件
        
        view.addSubview(composetextView)
        composetextView.addSubview(composeCollectionView)
        
        composetextView.snp_makeConstraints { (make) -> Void in
            
            
        make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        
        }
        
        //添加控件ToolBar:
        
        view.addSubview(composeToolBar)
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            
            make.bottom.right.leading.equalTo(view)
            make.height.equalTo(44)
            
        }
        
        composeCollectionView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(composetextView).offset(100)
            
            make.leading.equalTo(composetextView).offset(10)
            
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            
            
        }
        
        
        composeToolBar.clouseback = { [weak self]  (type: ComposeToolBarType) -> () in
            
            
            switch type {
            
            case ComposeToolBarType.Picture:
                
                 //访问相册:
                self?.selectImages()
                
            case .Mention:
                
                print("@")
                
            case.Trend:
                
                print("#")
                
            case.Emoticon:
                //点击按钮点击事件:
               self?.switchKeyboard()
                
                
            case.Add:
                
                print("+")
            
            
            }
        
        
        
        
        }
        composeCollectionView.clouseImageCallBack = { [weak self] ()->() in
            
            self?.selectImages()
        
      
        }
        //点击按钮点击事件:
        
        //通知键盘 然后更改toolbar的约束
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "KeyboardWillChangeFrame:", name:UIKeyboardWillChangeFrameNotification, object: nil)
        
        //表情按钮的删除通知:
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonClick", name: EmoticonDeleteNoti, object: nil)
     
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: EmoticonButtonNoti, object: nil)
        
        
    }
    
    
    
    //表情按钮点击事件(通知)
    
    func emoticonButtonClick(noti: NSNotification){
    
        guard let emoticon = noti.object as? TXFEmoticon else{
        return
        
        }
        if emoticon.isEmoji {
        
        composetextView.insertText(((emoticon.code ?? "")as NSString).emoji())
        
        
        }else{
        
            
            let oldAttr = NSMutableAttributedString(attributedString: composetextView.attributedText)
            
            let att = TXFTextAttachment()
            
            att.emoticon = emoticon
            
            let path = emoticon.path ?? ""
            
            let png = emoticon.png ?? ""
            
            let name = path + png
            
            att.image =  UIImage(named: name, inBundle: TXFEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            
            let lineHeight = composetextView.font!.lineHeight
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            
            let  attr = NSAttributedString(attachment: att)
            
            let selectRange = composetextView.selectedRange
            
            
            
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            
            oldAttr.addAttributes([NSFontAttributeName: composetextView.font!], range: NSRange(location: 0, length: oldAttr.length))
        composetextView.attributedText = oldAttr
            
            composetextView.selectedRange = NSRange(location: selectRange.location + 1 , length: 0)
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
        composetextView.delegate?.textViewDidChange!(composetextView)
            
            
            
        
        }
    
    
    }
    
    
    func deleteButtonClick(){
    
    composetextView.deleteBackward()
    
    
    }
    
    func switchKeyboard(){
        
        
//        print("哈哈哈")
        
    //设置键盘的辅助视图
        
        
        
        if composetextView.inputView == nil {
        
        composetextView.inputView = keyBoardView
        composeToolBar.isEmoticon = true
        
        }else{
        
        composetextView.inputView = nil
        composeToolBar.isEmoticon = false
        }
        //刷新
        
        composetextView.reloadInputViews()
        
        //让键盘成为第一响应者
        composetextView.becomeFirstResponder()
        
        
        
    }

    
    
    func KeyboardWillChangeFrame(noti: NSNotification){
    
    //键盘成为第一响应
        
    
    //得到键盘的高度
        
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]as! NSValue).CGRectValue()
        
    //更新约束
        
        composeToolBar.snp_updateConstraints { (make) -> Void in
            
        make.bottom.equalTo(view).offset(-(SCREENH - rect.origin.y))
            
        }
        //加动画
        
        UIView.animateWithDuration(0.25) { () -> Void in
        
            self.view.layoutIfNeeded()
        }
    
    
    }
    
    
    
    deinit{
    
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    //设置导航控制器
    func setupNav(){
        
        
    //导航控制器左侧按钮
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
        
    
    
    //导航控制器右侧按钮
     self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendClick")
    
       self.navigationItem.rightBarButtonItem?.enabled = false
    //创建中间的titleView(自定义)
     
    navigationItem.titleView = titleView
       
        
    }
    
    private lazy var titleView: UILabel = {
        
        let lab = UILabel()
        //从效果上看  lab是文字分成两行的 而且每一行的文字属性都不一样,因此我们可以通过富文本的形式进行设置
        
        let name  = TXFUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        //拼接完成\n标示换行
        let str = "发微博\n\(name)"
        
        //富文本转换
        
        let attr = NSMutableAttributedString(string: str)
        
        //获取range(我们要修改属性的文字)
        
        let range = (str as NSString).rangeOfString(name)
        
        //设置属性
        let ThemeColor = UIColor.orangeColor()
        
       
        attr.addAttributes([NSForegroundColorAttributeName: ThemeColor, NSFontAttributeName: UIFont.systemFontOfSize(11)], range: range)
        lab.attributedText = attr
        
        lab.textAlignment = .Center
        
        lab.numberOfLines = 0
        
        lab.sizeToFit()
        
        return lab
        
    }()
    
    //MARK: - 懒加载
    //懒加载textView
    
    private lazy var composetextView: TXFComposeTextView =  {
    let view = TXFComposeTextView()
    view.placehoder  = "关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博关注我的微博"
        //让控件可以滚动
    view.alwaysBounceVertical = true
    //遵循代理可以监控其响应时间 
        
    view.delegate = self
    //设置字体大小
    view.font = UIFont.systemFontOfSize(16)
    return view
    }()
    
    
    //懒加载下面的工具条
    
    private lazy var composeToolBar : TXFComposeToolBar =  TXFComposeToolBar()
    
    //懒加载collection控制器
    
    private lazy var composeCollectionView : TXFComposeCollection = TXFComposeCollection()
    
    
    
    private lazy var keyBoardView : TXFEmotionKeyBoardView  = {
    let view = TXFEmotionKeyBoardView()
    view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
    return view
    
    }()
    
    //取消
    
    func cancelClick(){
    
    dismissViewControllerAnimated(false, completion: nil)
    
    }
    
    //发送微博
    func sendClick(){
        
        var resultStr = ""
       
       composetextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composetextView.attributedText.length), options: []) { (dict, range, _) -> Void in
            
            // 如果是文本附件
            if let att = dict["NSAttachment"] as? TXFTextAttachment {
                resultStr += (att.emoticon?.chs ?? "")
            }else {
                // 文字
                let name = (self.composetextView.attributedText.string as NSString).substringWithRange(range)
                resultStr += name
            }
        }
        
    if composeCollectionView.imageList.count < 0 {
        
        //发送成功
        upload(resultStr)
      
        
    
    }else{
    
    //发送图片微博:
        
     update(resultStr)
        
    
   }
    
}
}
extension  TXFModelViewController{

    func update(status: String){
    
    
        //文字微博:
        TXFNetworkTools.shareTools.sendWBData(status, success: { (response) -> () in
            
            print("发送成功")
            
            }) { (error) -> () in
                
                print("发送失败\(error)")
        }
    
    

    
    
    }

    func upload(status: String){
    
    
        TXFNetworkTools.shareTools.sendWBImageData(status, imageList: composeCollectionView.imageList, success: { (response) -> () in
            
           
            
            
            print("发送成功")
            
            }, failure: { (error) -> () in
                print("发送失败")
        })
        
        
        
    }
    
    
    
    
    }




//Mark -代理方法
extension TXFModelViewController: UITextViewDelegate{
    //发生改变
    func textViewDidChange(textView: UITextView) {
      //右边的按钮是否禁用判断的标准就是是否有文字
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
     
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //滚动时候成为第一响应
        
        composetextView.resignFirstResponder()
        
    }


}





//访问相册
extension TXFModelViewController{

    
    func  selectImages(){
    
    let picker = UIImagePickerController()
        
    picker.delegate = self
     
    
    presentViewController(picker, animated: true, completion: nil)
    
    
    }
    


}

extension TXFModelViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{


//实现方法 获取访问图片
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
  
        composeCollectionView.addImages(scaleImageOfWidth(600, image: image))
        
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        
        
    }

    
    //压缩图片
    func scaleImageOfWidth(width: CGFloat, image: UIImage)->UIImage{
    
        if width > image.size.width {
        
        return image
        
        }
    
    let height = (width * image.size.height)/image.size.width
        
    let  rect  = CGRect(x: 0, y: 0, width: width, height: height)
        
      //开启上下文
        
        UIGraphicsBeginImageContext(rect.size)
        
    //将图片进行渲染
        
        image.drawInRect(rect)
        
        //获取上下文结果
        
        let imageResult = UIGraphicsGetImageFromCurrentImageContext()
        
    //关闭上下文
        
        UIGraphicsEndImageContext()
    
        return  imageResult
    
    
    }
    
    



}